<?
session_start();
if (!isSet($_SESSION['uid'])) {
    print "<meta http-equiv=\"refresh\" content=\"0;url=index.html\">";
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<title>小双快拼管理界面</title>
		<meta name="viewport" content="width=1280, user-scalable=no"/>  
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<link rel="stylesheet" href="style.css" />
        <link rel="stylesheet" href="exercise_management.css" />
        <script src="jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
			function before_submit(){
				var idstr = event.target.id;
				var exid_node = document.getElementById("ex_id");
				var act_node = document.getElementById("act");
				exid_node.value=idstr.substring(1, 2);
				act_node.value=idstr.substring(0, 1);
            }
            var contentTemplate;
            var currentTab;
            $(document).ready(function() {
                contentTemplate = $('#content-template').html();
                $('#content-template').remove();
                $('#content-panel').html(contentTemplate);
                currentTab = $('#tab-new-exercise');
            });
            var dict = new Object();
            var map_char_inputid = new Object();
            var incremental_id = 0;
            function update_dict(line_id) {
                    var prev_clip = $('#edit-content-clip-'+line_id).html();
                    reset_clip(line_id);
                    var text = $('#edit-content-'+line_id).val();
                    var forInquisition = "";
                    for (var i = 0; i < text.length; i++) {
                            if (dict[text[i]] == undefined ||
                                // keep existing
                                prev_clip.indexOf('<span>'+text[i]) > -1) {
                                forInquisition += text[i] + ' ';
                        }
                    }
                    // remove removed
                    var start = 0;
                    var pos;
                    console.log(prev_clip);
                    while ((pos = prev_clip.indexOf('<span>', start)) != -1) {
                            pos += '<span>'.length;
                            start = pos+1;
                            var character = prev_clip.substring(pos, pos+1);
                            if (text.indexOf(character) == -1) {
                                console.log('remove '+character);
                                dict[character] = undefined;
                                map_char_inputid[character] = undefined;
                            }
                    }
                    if (forInquisition.length != 0) {
                        var xhr = new XMLHttpRequest();
                        xhr.onreadystatechange = function() {
                            var result = xhr.responseText;
                            var showClip = false;
                            // data format: unrecognized_chars,recognized_chars
                            var p;
                            for (p = 0; p < result.length && result[p] != ','; p++) {
                                dict[result[p]] = false;
                                append_clip(line_id, result[p]);
                                if (!showClip) showClip = true;
                            }
                            for (; p < result.length; p++) {
                                dict[result[p]] = true;
                            }
                            if (showClip) show_clip(line_id);
                        }
                        xhr.open('POST', 'search_dic.php', true);
                        xhr.send(forInquisition);
                    }
            }
            function reset_clip(line_id) {
                    $('#edit-content-clip-'+line_id).hide();
                    $('#edit-content-clip-'+line_id).html('<span>有生字，请标注^_^~~</span>');
            }
            function append_clip(line_id, character) {
                    $('#edit-content-clip-'+line_id).append( '<span>'+character+':&nbsp;</span>');
                    incremental_id++;
                    var input = '<input type="text" id="input-'+incremental_id+'" class="text-field" style="width:50px" maxlength="2" />';
                    map_char_inputid[character] = 'input-'+incremental_id;
                    $('#edit-content-clip-'+line_id).append(input);
            }
            function show_clip(id) {
                    $('#edit-content-clip-'+id+':hidden').toggle(200);
            }
            function append_line(id) {
                    if ($('#edit-content-'+id).length == 0) {
                        var newLine = $('<input type="text" class="text-field full-width" id="edit-content-'+id+'" onblur="update_dict('+id+')" onfocus="append_line('+(id+1)+')" />');
                        var newClip = $('<div id="edit-content-clip-'+id+'" class="clipline">'+
                                '<span>有生字，请标注^_^~~</span>'+
                                '</div>');
                        $('#edit-content').append(newLine);
                        $('#edit-content').append(newClip);
                        newLine.hide();
                        newLine.toggle(200);
                    }
            }
            function tab_to_exercise(tab, id) {
                    currentTab.css('border-right', '1px solid #333');
                    currentTab.css('background-image', 'none');
                    tab.css('border-right', '0px');
                    tab.css('background-image', 'url(paper.jpg)');
                    currentTab = tab;
                    dict = new Object();
                    map_char_inputid = new Object();
                    if (id > 0) {
                            load_exercise(id);
                    } else {
                            new_exercise();
                    }
            }
            function load_exercise(id) {
                    // Abort unsaved change
                    $('#content-panel').html(contentTemplate);
                    var xhr = new XMLHttpRequest();
                    xhr.onreadystatechange = function() {
                        var result = xhr.responseText;
                        var resultArray = result.split('\n');
                        $('#input-title').val(resultArray[0]);
                        $('#input-description').val(resultArray[1]);
                        var ln = 0;
                        for (var i = 2; i < resultArray.length; i++) {
                                ln++;
                                inputLine = $('#edit-content-'+ln);
                                if (inputLine.length == 0) {
                                    append_line(ln);
                                }
                                $('#edit-content-'+ln).val(resultArray[i]);
                        }
                    };
                    xhr.open('POST', 'load_exercise.php');
                    xhr.send(id);
            }
            function new_exercise() {
                    $('#content-panel').html(contentTemplate);
            }
            function submit() {
                    
                    var marked = '';
                    for (var character in dict) if (dict[character] == false) {
                        console.log('char='+character);
                        var input = map_char_inputid[character];
                        if ($('#'+input).val().length != 2) {
                            alert('请为"'+character+'"字注音~');
                            return;
                        }
                        marked += character + ' ' + $('#'+input).val()+'\n';
                    }

                    var xhr = new XMLHttpRequest();
                    xhr.onreadystatechange = function() {
                        if (xhr.readyState != 4) return;

                        var xhr0 = new XMLHttpRequest();
                        xhr0.onreadystatechange = function() {
                            if (xhr0.readyState != 4) return;    
                            location.reload();
                        }         
                        xhr0.open('POST', 'save_exercise.php', false);
                        var postData;
                        var currentTabName = currentTab.attr('id');
                        if (currentTabName == 'tab-new-exercise') {
                            postData = '0\n';
                        } else {
                            postData = currentTabName.substring(currentTabName.lastIndexOf('-')+1) + '\n';
                        }
                        postData += $('#input-title').val() + '\n'
                                + $('#input-description').val() + '\n';
                        var ln = 1;
                        while ($('#edit-content-'+ln).length > 0) {
                            var line = $('#edit-content-'+ln).val();
                            line = jQuery.trim(line);
                            if (line) {
                                postData += line + '\n';
                            }
                            ln++;
                        }
                        xhr0.send(postData);
                    }
                    xhr.open('POST', 'update_dic.php');
                    xhr.send(marked);
            }
            function delete_exercise() {
                var currentTabName = currentTab.attr('id');
                if (currentTabName == 'tab-new-exercise') {
                    var r = confirm('确认重置？');
                    if (r) {
                        dict = new Object();
                        map_char_inputid = new Object();
                        new_exercise();                        
                    }
                } else { 
                    var r = confirm('确认删除此练习吗？本操作不可恢复！');
                    if (r) {
                        var xhr = new XMLHttpRequest();
                        xhr.onreadystatechange = function() {
                            if (xhr.readyState != 4) return;
                            location.reload();
                        }
                        xhr.open('POST', 'delete_exercise.php');
                        var id = currentTabName.substring(currentTabName.lastIndexOf('-')+1);
                        xhr.send(id);
                    }
                }
            }
        </script>
	</head>
	<body>
<?
$db = mysql_connect("localhost", "usr_2012_16", "se09member");
if (!$db) {
	print "Error - Could not connect to MySQL";
	exit;
}
$er = mysql_select_db("db_2012_16");
if (!$er) {
	print "Error - Could not select the database db_2012_16";
	exit;
}

$query = "select * from se_exercise_meta;";
$result = mysql_query($query);
if (!$result) {
	print "Error - the query could not be executed";
	$error = mysql_error();
	print "<p>" . $error . "</p>";
	exit;
}
?>
		<div id="left-panel">
			<div id="admin-info">
                <h2><? print $_SESSION['nick_name']; ?></h2>
                <a href="logout.php"><div class="fake_link">注销</div></a>
			</div>
			<div id="tab-new-exercise" class="list-item clickable" onClick="tab_to_exercise($('#tab-new-exercise'), 0)">新练习</div>
<?
	while($row = mysql_fetch_array($result)){
		$id = $row['id'];
		$title = $row['title'];
		$description = $row['description'];
?>
            <div id="tab-exercise-<? print $id ?>" class="list-item clickable" style="border-right:1px solid #333" onClick="tab_to_exercise($('#tab-exercise-<? print $id ?>'), <? print $id ?>)"><? echo $row['title']; ?></div>
<?
	}
?>
		</div>

		<div id="content-panel">	
		</div>

        <div id="content-template">
			<div id="content-edit-exercise">
                <div class="list-item">
                    <div class="title">标题</div> 
                    <div><input id="input-title" type="text" class="text-field full-width" id="edit-title" /></div>
                </div>
                <div class="list-item">
                    <div class="title">描述</div>
                    <div>
                        <textarea class="text-field full-width" id="input-description" style="padding:5px; height:45px; line-height:15px; resize:none" /></textarea>
                    </div> 
                </div>
                <div id="edit-content" class="list-item" style="border: 0px">
                    <div class="title">练习内容</div>
                    <input type="text" class="text-field full-width" id="edit-content-1" onchange="update_dict(1)" onfocus="append_line(2)" />
                    <div id="edit-content-clip-1" class="clipline">
                        <span>有生字，请标注^_^~~</span>
                    </div>
                    <input type="text" class="text-field full-width" id="edit-content-2" onchange="update_dict(2)" onfocus="append_line(3)" />
                    <div id="edit-content-clip-2" class="clipline">
                        <span>有生字，请标注^_^~~</span>
                    </div>
                </div>
            </div>
            <button id="submit" class="button long" style="margin-bottom:50px" onClick="submit()">提交</button>
            <button id="delete-ex" class="button_red long" style="margin-bottom:50px; margin-left:20px" onClick="delete_exercise()">删除</button>       
        </div>

	</body>
</html>
